import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**客户端自定义存储属性枚举*/
export const enum E_ClientStorage {
	/**数据*/
	INFO = 0,
	/**枚举数量*/
	EnumCount = 1
}


/**客户端自定义存储*/
export class ClientStorage {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_CLIENT_STORAGE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_CLIENT_STORAGE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ClientStorage[] = [];

	/**创建入口*/
	public static create(json?: string): ClientStorage {
		const c = this.POOL.pop() || new ClientStorage();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**数据*/
	protected _info: HashMap<string, string> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ClientStorage.POOL.indexOf(this) === -1) {
			ClientStorage.POOL.push(this);
		}
	}

	/**设置数据*/
	public putInfo(k: string, v: string): string {
		const ov = this._info.put(k, v);
		return ov;
	}


	/**获取数据*/
	public getInfo(k: string) {
		return this._info.get(k);
	}


	/**删除数据*/
	public removeInfo(k: string): string {
		const ov = this._info.remove(k);
		return ov;
	}


	/**获取数据映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getInfoKeys(): string[] {
		return this._info.getKeys();
	}


	/**获取数据映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getInfoValues(): string[] {
		return this._info.getValues();
	}


	/**清空数据映射表*/
	public clearInfoMap(): void {
		this._info.clear();
	}



	/**通过枚举获取值*/
	public getV(k: E_ClientStorage): any {
		switch (k) {
			case E_ClientStorage.INFO: return this._info;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ClientStorage, v: any): void {
		switch (k) {
			case E_ClientStorage.INFO: this._info = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//数据
		if (this._info) {
			this._info.clear();
		}
		else {
			this._info = new HashMap<string, string>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._info.size() > 0) {
			const ks = this._info.getKeys();
			const vs = this._info.getValues();
			json.info = [ks, vs];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.info) {
			const ks: string[] = json.info[0];
			const vs: string[] = json.info[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._info.setKeyAndValueList(ks, vs);
			}
			else if (json.info.getKeys && json.info.getValues) {	//结构体
				const ks2 = json.info.getKeys();
				const vs2 = json.info.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._info.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//数据
		{
			const ks = this._info.getKeys();
			const vs = this._info.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeString(ks[i]);
				byte.writeString(vs[i]);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//数据
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readString();
				const v = byte.readString();
				this._info.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): ClientStorage {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ClientStorage.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ClientStorage.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];

			//数据
			if (idx === E_ClientStorage.INFO) {
				const k: string = us[i + 1];
				const newv :string = us[i + 2];
				const oldv = this.putInfo(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in ClientStorage with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ClientStorage): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//数据
		{
			const idx = E_ClientStorage.INFO;
			const ks1 = this._info.getKeys();
			const ks2 = other._info.getKeys();
			const vs1 = this._info.getValues();
			const vs2 = other._info.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getInfo(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getInfo(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ClientStorage.TOTAL_EVENT_ID, this.getV(0));
	}

}
